// API服务配置
export const API_BASE_URL = 'http://localhost:8000/api'

// 通用API请求函数
const apiRequest = async (url, options = {}) => {
  const config = {
    headers: {
      'Content-Type': 'application/json',
      ...options.headers,
    },
    ...options,
  }

  try {
    const response = await fetch(`${API_BASE_URL}${url}`, config)
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    // 检查响应是否有内容，DELETE请求通常返回空响应
    const contentType = response.headers.get('content-type')
    if (response.status === 204 || !contentType || !contentType.includes('application/json')) {
      return null
    }
    
    const data = await response.json()
    return data
  } catch (error) {
    console.error('API request failed:', error)
    throw error
  }
}

// 人员管理API
export const personnelAPI = {
  // 获取所有人员
  getAll: () => apiRequest('/personnel/'),
  
  // 获取单个人员
  getById: (id) => apiRequest(`/personnel/${id}/`),
  
  // 创建新人员
  create: (data) => apiRequest('/personnel/', {
    method: 'POST',
    body: JSON.stringify(data),
  }),
  
  // 更新人员信息
  update: (id, data) => apiRequest(`/personnel/${id}/`, {
    method: 'PUT',
    body: JSON.stringify(data),
  }),
  
  // 部分更新人员信息
  patch: (id, data) => apiRequest(`/personnel/${id}/`, {
    method: 'PATCH',
    body: JSON.stringify(data),
  }),
  
  // 删除人员
  delete: (id) => apiRequest(`/personnel/${id}/`, {
    method: 'DELETE',
  }),
}

// 设备管理API
export const equipmentAPI = {
  // 获取所有设备
  getAll: () => apiRequest('/equipment/'),
  
  // 获取单个设备
  getById: (id) => apiRequest(`/equipment/${id}/`),
  
  // 创建新设备
  create: (data) => apiRequest('/equipment/', {
    method: 'POST',
    body: JSON.stringify(data),
  }),
  
  // 更新设备信息
  update: (id, data) => apiRequest(`/equipment/${id}/`, {
    method: 'PUT',
    body: JSON.stringify(data),
  }),
  
  // 删除设备
  delete: (id) => apiRequest(`/equipment/${id}/`, {
    method: 'DELETE',
  }),
}

// 周会待办事项API
export const weeklyTodoAPI = {
  // 获取所有待办事项
  getAll: () => apiRequest('/weekly-todos/'),
  
  // 获取单个待办事项
  getById: (id) => apiRequest(`/weekly-todos/${id}/`),
  
  // 创建新待办事项
  create: (data) => apiRequest('/weekly-todos/', {
    method: 'POST',
    body: JSON.stringify(data),
  }),
  
  // 批量创建待办事项
  bulkCreate: (data) => apiRequest('/weekly-todos/bulk_create/', {
    method: 'POST',
    body: JSON.stringify(data),
  }),
  
  // 更新待办事项
  update: (id, data) => apiRequest(`/weekly-todos/${id}/`, {
    method: 'PUT',
    body: JSON.stringify(data),
  }),
  
  // 部分更新待办事项
  patch: (id, data) => apiRequest(`/weekly-todos/${id}/`, {
    method: 'PATCH',
    body: JSON.stringify(data),
  }),
  
  // 删除待办事项
  delete: (id) => apiRequest(`/weekly-todos/${id}/`, {
    method: 'DELETE',
  }),
  
  // 按闭环状态获取待办事项
  getByClosure: (status) => apiRequest(`/weekly-todos/by_closure/?status=${status}`),
  
  // 按责任人获取待办事项
  getByPerson: (person) => apiRequest(`/weekly-todos/by_person/?person=${person}`),
  
  // 获取统计信息
  getStatistics: () => apiRequest('/weekly-todos/statistics/'),
}

// 关键备件库存API
export const keyPartsAPI = {
  // 获取所有关键备件
  getAll: () => apiRequest('/key-parts/'),
  
  // 获取单个关键备件
  getById: (id) => apiRequest(`/key-parts/${id}/`),
  
  // 创建新关键备件记录
  create: (data) => apiRequest('/key-parts/', {
    method: 'POST',
    body: JSON.stringify(data),
  }),
  
  // 更新关键备件记录
  update: (id, data) => apiRequest(`/key-parts/${id}/`, {
    method: 'PUT',
    body: JSON.stringify(data),
  }),
  
  // 部分更新关键备件记录
  patch: (id, data) => apiRequest(`/key-parts/${id}/`, {
    method: 'PATCH',
    body: JSON.stringify(data),
  }),
  
  // 删除关键备件记录
  delete: (id) => apiRequest(`/key-parts/${id}/`, {
    method: 'DELETE',
  }),
  
  // 按物品名称查询
  getByItem: (itemName) => apiRequest(`/key-parts/by_item/?item_name=${encodeURIComponent(itemName)}`),
  
  // 获取库存统计
  getStatistics: () => apiRequest('/key-parts/statistics/'),
  
  // 批量创建记录
  bulkCreate: (dataList) => apiRequest('/key-parts/bulk_create/', {
    method: 'POST',
    body: JSON.stringify(dataList),
  }),
}

// 日工作计划API
export const dailyWorkPlanAPI = {
  // 获取所有工作计划
  getAll: () => apiRequest('/daily-work-plans/'),
  
  // 获取单个工作计划
  getById: (id) => apiRequest(`/daily-work-plans/${id}/`),
  
  // 创建新工作计划
  create: (data) => apiRequest('/daily-work-plans/', {
    method: 'POST',
    body: JSON.stringify(data),
  }),
  
  // 批量保存工作计划
  bulkSave: (data) => apiRequest('/daily-work-plans/bulk_save/', {
    method: 'POST',
    body: JSON.stringify(data),
  }),
  
  // 更新工作计划
  update: (id, data) => apiRequest(`/daily-work-plans/${id}/`, {
    method: 'PUT',
    body: JSON.stringify(data),
  }),
  
  // 部分更新工作计划
  patch: (id, data) => apiRequest(`/daily-work-plans/${id}/`, {
    method: 'PATCH',
    body: JSON.stringify(data),
  }),
  
  // 删除工作计划
  delete: (id) => apiRequest(`/daily-work-plans/${id}/`, {
    method: 'DELETE',
  }),
  
  // 按日期范围获取工作计划
  getByDateRange: (startDate, endDate) => apiRequest(`/daily-work-plans/get_by_date_range/?start_date=${startDate}&end_date=${endDate}`),
  
  // 获取最近7天的工作计划
  getRecentPlans: () => apiRequest('/daily-work-plans/get_recent_plans/'),
  
  // 按日期获取工作计划
  getByDate: (date) => apiRequest(`/daily-work-plans/?date=${date}`),
  
  // 按实验类型获取工作计划
  getByExperimentType: (experimentType) => apiRequest(`/daily-work-plans/?experiment_type=${encodeURIComponent(experimentType)}`),
  
  // 钉钉机器人推送
  pushToDingTalk: (data) => apiRequest('/daily-work-plans/push_to_dingtalk/', {
    method: 'POST',
    body: JSON.stringify(data),
  }),
}

// 试验统计API
export const experimentStatisticsAPI = {
  // 获取所有试验记录
  getAll: () => apiRequest('/experiment-statistics/experiments/'),
  
  // 获取单个试验记录
  getById: (id) => apiRequest(`/experiment-statistics/experiments/${id}/`),
  
  // 创建新试验记录
  create: (data) => apiRequest('/experiment-statistics/experiments/', {
    method: 'POST',
    body: JSON.stringify(data),
  }),
  
  // 更新试验记录
  update: (id, data) => apiRequest(`/experiment-statistics/experiments/${id}/`, {
    method: 'PUT',
    body: JSON.stringify(data),
  }),
  
  // 部分更新试验记录
  patch: (id, data) => apiRequest(`/experiment-statistics/experiments/${id}/`, {
    method: 'PATCH',
    body: JSON.stringify(data),
  }),
  
  // 删除试验记录
  delete: (id) => apiRequest(`/experiment-statistics/experiments/${id}/`, {
    method: 'DELETE',
  }),
  
  // 获取试验分类列表
  getCategories: () => apiRequest('/experiment-statistics/experiments/categories/'),
  
  // 获取统计信息
  getStatistics: () => apiRequest('/experiment-statistics/experiments/statistics/'),
  
  // 添加附件
  addAttachment: (experimentId, attachmentData) => {
    const isFormData = attachmentData instanceof FormData;
    
    return fetch(`${API_BASE_URL}/experiment-statistics/experiments/${experimentId}/add_attachment/`, {
      method: 'POST',
      headers: isFormData ? {} : {
        'Content-Type': 'application/json',
      },
      body: isFormData ? attachmentData : JSON.stringify(attachmentData),
    }).then(response => {
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      return response.json();
    });
  },
  
  // 获取试验附件
  getAttachments: (experimentId) => apiRequest(`/experiment-statistics/experiments/${experimentId}/attachments/`),
  
  // 下载附件
  downloadAttachment: (attachmentId) => {
    return fetch(`${API_BASE_URL}/experiment-statistics/attachments/${attachmentId}/download/`, {
      method: 'GET',
    }).then(response => {
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      return response.blob();
    });
  },
  
  // 预览附件
  previewAttachment: (attachmentId) => {
    return `${API_BASE_URL}/experiment-statistics/attachments/${attachmentId}/preview/`;
  },
  
  // 删除附件
  deleteAttachment: (attachmentId) => apiRequest(`/experiment-statistics/attachments/${attachmentId}/`, {
    method: 'DELETE',
  }),
}

// 试验计划管理API
export const experimentPlanningAPI = {
  // 设备管理 - 使用personnel模块的设备API
  equipment: equipmentAPI,
  
  // 试验计划管理
  experimentPlan: {
    // 获取所有试验计划
    getAll: () => apiRequest('/experiment-planning/api/experiment-plans/'),
    
    // 获取甘特图数据
    getGanttData: () => apiRequest('/experiment-planning/api/experiment-plans/gantt_data/'),
    
    // 获取单个试验计划
    getById: (id) => apiRequest(`/experiment-planning/api/experiment-plans/${id}/`),
    
    // 创建新试验计划
    create: (data) => apiRequest('/experiment-planning/api/experiment-plans/', {
      method: 'POST',
      body: JSON.stringify(data),
    }),
    
    // 更新试验计划
    update: (id, data) => apiRequest(`/experiment-planning/api/experiment-plans/${id}/`, {
      method: 'PUT',
      body: JSON.stringify(data),
    }),
    
    // 更新试验时间
    updateDates: (id, data) => apiRequest(`/experiment-planning/api/experiment-plans/${id}/update_dates/`, {
      method: 'PATCH',
      body: JSON.stringify(data),
    }),
    
    // 删除试验计划
    delete: (id) => apiRequest(`/experiment-planning/api/experiment-plans/${id}/`, {
      method: 'DELETE',
    }),
    
    // 从调度系统同步数据
    syncFromSchedulingSystem: () => apiRequest('/experiment-planning/api/experiment-plans/sync_from_scheduling_system/', {
      method: 'POST',
    }),
    
    // 从钉钉同步数据
    syncFromDingtalk: () => apiRequest('/experiment-planning/api/experiment-plans/sync_from_dingtalk/', {
      method: 'POST',
    }),
  },
}

// 设备维护管理API
export const equipmentMaintenanceAPI = {
  // 维修记录管理
  repairRecords: {
    getAll: (url = '/equipment-maintenance/repair-records/') => apiRequest(url),
    create: (recordData) => apiRequest('/equipment-maintenance/repair-records/', {
      method: 'POST',
      body: JSON.stringify(recordData),
    }),
    update: (id, recordData) => apiRequest(`/equipment-maintenance/repair-records/${id}/`, {
      method: 'PUT',
      body: JSON.stringify(recordData),
    }),
    delete: (id) => apiRequest(`/equipment-maintenance/repair-records/${id}/`, {
      method: 'DELETE',
    }),
    importWord: (formData) => apiRequest('/equipment-maintenance/repair-records/import_word/', {
      method: 'POST',
      body: formData,
      headers: {}, // 清空headers，让浏览器自动设置multipart/form-data
    }),
    exportWord: async (id) => {
      const response = await fetch(`${API_BASE_URL}/equipment-maintenance/repair-records/${id}/export_word/`, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        },
      })
      
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }
      
      return response.blob()
    },
  },

  // 维保记录管理
  maintenanceItems: {
    getAll: (url = '/equipment-maintenance/maintenance-items/') => apiRequest(url),
    create: (itemData) => apiRequest('/equipment-maintenance/maintenance-items/', {
      method: 'POST',
      body: JSON.stringify(itemData),
    }),
    batchCreate: (itemsData) => apiRequest('/equipment-maintenance/maintenance-items/batch_create/', {
      method: 'POST',
      body: JSON.stringify(itemsData),
    }),
    update: (id, itemData) => apiRequest(`/equipment-maintenance/maintenance-items/${id}/`, {
      method: 'PUT',
      body: JSON.stringify(itemData),
    }),
    delete: (id) => apiRequest(`/equipment-maintenance/maintenance-items/${id}/`, {
      method: 'DELETE',
    }),
  },

  // 维修记录附图管理
  repairRecordImages: {
    getAll: (repairRecordId) => apiRequest(`/equipment-maintenance/repair-record-images/?repair_record=${repairRecordId}`),
    upload: (formData) => apiRequest('/equipment-maintenance/repair-record-images/', {
      method: 'POST',
      body: formData,
      headers: {}, // 清空headers，让浏览器自动设置multipart/form-data
    }),
    batchUpload: (formData) => apiRequest('/equipment-maintenance/repair-record-images/batch_upload/', {
      method: 'POST',
      body: formData,
      headers: {}, // 清空headers，让浏览器自动设置multipart/form-data
    }),
    delete: (id) => apiRequest(`/equipment-maintenance/repair-record-images/${id}/`, {
      method: 'DELETE',
    }),
    download: (id) => {
      const url = `${API_BASE_URL}/equipment-maintenance/repair-record-images/${id}/download/`
      window.open(url, '_blank')
    },
    preview: (id) => {
      return `${API_BASE_URL}/equipment-maintenance/repair-record-images/${id}/preview/`
    },
  },
}

export default {
  personnelAPI,
  equipmentAPI,
  weeklyTodoAPI,
  keyPartsAPI,
  dailyWorkPlanAPI,
  experimentStatisticsAPI,
  experimentPlanningAPI,
  equipmentMaintenanceAPI,
}